package com.sjgtw.cloud.web.duty.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.duty.domain.Duty;
import com.sjgtw.cloud.web.duty.domain.DutyDetails;
import com.sjgtw.cloud.web.duty.mapper.DutyDetailsMapper;
import com.sjgtw.cloud.web.duty.mapper.DutyMapper;
import com.sjgtw.cloud.web.duty.service.IDutyService;
import com.sjgtw.cloud.web.duty.vo.DutyImportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 值班表Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-13
 */
@Service
public class DutyServiceImpl implements IDutyService
{
    @Autowired
    private DutyMapper dutyMapper;

    @Autowired
    private DutyDetailsMapper dutyDetailsMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SystemServerService systemServerService;

    /**
     * 查询值班表
     * 
     * @param id 值班表主键
     * @return 值班表
     */
    @Override
    public Duty selectDutyById(Long id)
    {
        return dutyMapper.selectDutyById(id);
    }

    /**
     * 查询值班表列表
     * 
     * @param duty 值班表
     * @return 值班表
     */
    @Override
    public List<Map<String, Object>>  selectDutyList(Duty duty)
    {

        List<Map<String, Object>> maps1 = dutyDetailsMapper.selectAllDuty(new DutyDetails());

        // 查出所有单位的值班总表记录
        /*List<Map<String, Object>> maps = dutyMapper.selectDutyList(duty);

        JSONArray jsonArray =new JSONArray();
        Set<JSONObject> sets = new HashSet<>();
        if(maps.size()>0){

            for (int i = 0; i < maps.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("deptId",maps.get(i).get("deptId"));
                jsonObject.put("deptName",maps.get(i).get("deptName"));
                sets.add(jsonObject);
                //resultArray.add(jsonObject);
            }
            // 去重，看有几个单位

            Map<Object, List<Map<String, Object>>> collect = maps.stream().collect(groupingBy(item -> item.get("deptId")));


            if(collect!=null){

                collect.forEach((k, v) -> {
                    // k 是单位， v 是有几个小组,使用v 查出每个小组下的人员详情
                    HashMap<Object, Object> result = new HashMap<>();
                    v.stream().forEach(item -> {
                        Long dutyId = (Long) item.get("dutyId");
                        DutyDetails dutyDetails1 = new DutyDetails();
                        dutyDetails1.setDutyId(dutyId);
                        List<Map<String,Object>> dutyDetails = dutyDetailsMapper.selectDutyDetailsList(dutyDetails1);
                        result.put(dutyId,dutyDetails);
                    });

                    for (JSONObject set : sets) {
                        if(set.getLong("deptId").equals(k)){
                            set.put("details",result);
                        }
                    }

                });
            }
            for(JSONObject s:sets){
                jsonArray.add(s);
            }
        }
*/

        return maps1;
    }

    @Override
    public List<DutyImportVo> selectDutyExportList(DutyImportVo dutyImportVo) {
        List<DutyImportVo> dutyImportVos = dutyDetailsMapper.selectDutyExportList(dutyImportVo);
        if(dutyImportVos.size()>0){
            for (int i = 0; i < dutyImportVos.size(); i++) {
                DutyImportVo dutyImportVo1 = dutyImportVos.get(i);

                if(StringUtils.isNotEmpty(dutyImportVo1.getJune())){
                    String[] juneSpilt = dutyImportVo1.getJune().split(",");
                    String outJune = "";
                    if(juneSpilt.length>0){
                        for (String s : juneSpilt) {
                            outJune += s.substring(s.length()-2)+"、";
                        }
                    }
                    dutyImportVo1.setJune(outJune.substring(0,outJune.length()-1));
                }

                if(StringUtils.isNotEmpty(dutyImportVo1.getJuly())){
                    String[] julySpilt = dutyImportVo1.getJuly().split(",");
                    String outJuly = "";
                    if(julySpilt.length>0){
                        for (String s : julySpilt) {
                            outJuly += s.substring(s.length()-2)+"、";
                        }
                    }
                    dutyImportVo1.setJuly(outJuly.substring(0,outJuly.length()-1));
                }

                if(StringUtils.isNotEmpty(dutyImportVo1.getAugust())){
                    String[] augustSpilt = dutyImportVo1.getAugust().split(",");
                    String outAugust = "";
                    if(augustSpilt.length>0){
                        for (String s : augustSpilt) {
                            outAugust += s.substring(s.length()-2)+"、";
                        }
                    }
                    dutyImportVo1.setAugust(outAugust.substring(0,outAugust.length()-1));
                }


                if(StringUtils.isNotEmpty(dutyImportVo1.getSeptember())){
                    String[] septemberSpilt = dutyImportVo1.getSeptember().split(",");
                    String outSeptember = "";
                    if(septemberSpilt.length>0){
                        for (String s : septemberSpilt) {
                            outSeptember += s.substring(s.length()-2)+"、";
                        }
                    }
                    dutyImportVo1.setSeptember(outSeptember.substring(0,outSeptember.length()-1));
                }

            }
        }
        return dutyImportVos;
    }

    /**
     * 新增值班表
     * 
     * @param duty 值班表
     * @return 结果
     */
    @Override
    public int insertDuty(Duty duty)
    {
        return dutyMapper.insertDuty(duty);
    }

    @Override
    public int addOrEdit(JSONObject jsonObject) {

        if(jsonObject.getLong("id") != null){
            // 说明是编辑，先把之前的都删了
            dutyDetailsMapper.deleteDutyDetailsById(jsonObject.getLong("id"));
        }

        Long deptId = jsonObject.getLong("deptId");
        Duty duty1 = dutyMapper.selectDutyByDeptId(deptId);
        Long newDutyId;
        if(duty1 != null){
            newDutyId = duty1.getId();
        }else{
            Duty duty = new Duty();
            duty.setDeptId(deptId);
            dutyMapper.insertDuty(duty);
            newDutyId =duty.getId();
        }

        String workerIdList = jsonObject.getString("workerIdList");
        String dateList = jsonObject.getString("dateList");

        String june ="";
        String july ="";
        String august ="";
        String september ="";

        if(StringUtils.isNotEmpty(dateList)){
            String[] dateArray = dateList.split(",");
            for (String s : dateArray) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date parse = simpleDateFormat.parse(s);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(parse);
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始，需要加1
                    int day = calendar.get(Calendar.DAY_OF_MONTH);

                    if(isSameMonth(year,month,day,6)){
                        june += s+",";
                    }
                    if(isSameMonth(year,month,day,7)){
                        july += s+",";
                    }
                    if(isSameMonth(year,month,day,8)){
                        august += s+",";
                    }
                    if(isSameMonth(year,month,day,9)){
                        september += s+",";
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

        }


        if(StringUtils.isNotEmpty(workerIdList)){
            String[] workIds = workerIdList.split(",");
            for (int i = 0; i < workIds.length; i++) {

                DutyDetails dutyDetails1 = dutyDetailsMapper.selectByDutyIdAndWorkId(newDutyId, Long.valueOf(workIds[i]));
                if(dutyDetails1 != null){
                    dutyDetailsMapper.deleteDutyDetailsById(dutyDetails1.getId());
                }

                DutyDetails dutyDetails = new DutyDetails();
                dutyDetails.setAugust(august);
                dutyDetails.setJune(june);
                dutyDetails.setSeptember(september);
                dutyDetails.setJuly(july);
                dutyDetails.setDutyId( newDutyId);
                dutyDetails.setWorkerId(Long.valueOf(workIds[i]));
                dutyDetailsMapper.insertDutyDetails(dutyDetails);

            }
        }

        return 1;
    }

    @Override
    public int deleteDuty(Long id) {
        dutyDetailsMapper.deleteDutyDetailsById(id);
        //dutyMapper.deleteDutyById(dutyId);
        return 1;
    }

    @Override
    public List<Map<String,Object>> getUserDuty(Long workerId) {
        DutyDetails dutyDetails1 = new DutyDetails();
        dutyDetails1.setWorkerId(workerId);
        List<Map<String,Object>> dutyDetails = dutyDetailsMapper.selectDutyDetailsList(dutyDetails1);

        return dutyDetails;
    }

    public static boolean isSameMonth(int year, int month, int day, int targetMonth) {

        Date nowTime = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowTime);
        int nowYear = calendar.get(Calendar.YEAR);
        int nowMonth = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始，需要加1

        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, day);
        int currentMonth = cal.get(Calendar.MONTH) + 1;
        int i = 0;
        boolean istrue = currentMonth == targetMonth && nowYear == year && day < 32 && day > 0 ;
        return istrue;
    }

    /**
     * 修改值班表
     * 
     * @param duty 值班表
     * @return 结果
     */
    @Override
    public int updateDuty(Duty duty)
    {
        return dutyMapper.updateDuty(duty);
    }

    /**
     * 批量删除值班表
     * 
     * @param ids 需要删除的值班表主键
     * @return 结果
     */
    @Override
    public int deleteDutyByIds(Long[] ids)
    {
        return dutyMapper.deleteDutyByIds(ids);
    }

    /**
     * 删除值班表信息
     * 
     * @param id 值班表主键
     * @return 结果
     */
    @Override
    public int deleteDutyById(Long id)
    {
        return dutyMapper.deleteDutyById(id);
    }

    @Override
    public List<String> check(List<DutyImportVo> entities) {

        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> userNames = extractAndDeduplicateUserNames(entities);

        AjaxResult userResult = systemServerService.getUserByNames(StringUtils.join(userNames, ","));
        Map<String, Long> userMap = new HashMap<>();
        if (userResult != null) {
            Object object = userResult.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        userMap.put(json.getString("userName"), json.getLong("userId"));
                    }
                }
            }
        }


        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (DutyImportVo entity : entities) {
            System.out.println(entity.getNum()+"------------------------");
            if (StringUtils.isEmpty(entity.getDeptName())) {
                errors.add("序号为" + entity.getNum() + "行数据单位不能为空");
            } else if (deptMap.containsKey(entity.getDeptName())) {
                entity.setDeptId(deptMap.get(entity.getDeptName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据单位不存在");
            }

            if (StringUtils.isEmpty(entity.getWorker())) {
                errors.add("序号为" + entity.getNum() + "行数据值班人员姓名不能为空");
            } else if (userMap.containsKey(entity.getWorker())) {
                entity.setWorkerId(userMap.get(entity.getWorker()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据值班人员姓名不存在");
            }

            String june ="";
            String july ="";
            String august ="";
            String september ="";

            Date nowDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(nowDate);
            int year = calendar.get(Calendar.YEAR);

            if (StringUtils.isNotEmpty(entity.getJune())) {
                String[] juneSplit = entity.getJune().split("、");
                String juneString = "";
                for (String s : juneSplit) {

                    if(Integer.valueOf(s) > 30){
                        errors.add("序号为" + entity.getNum() + "行数据六月值班日期有误");
                    }
                    String day = "";
                    if(s.length()==1){
                        day= year+"-06"+"-0"+s;
                    }else  if(s.length()==2){
                        day = year+"-06"+"-"+s;
                    }
                    juneString +=day+",";
                }
                entity.setJune(juneString.substring(0,juneString.length()-1));
            }

            if (StringUtils.isNotEmpty(entity.getJuly())) {
                String[] julySplit = entity.getJuly().split("、");
                String julyString = "";
                for (String s : julySplit) {
                    if(Integer.valueOf(s) > 31){
                        errors.add("序号为" + entity.getNum() + "行数据七月值班日期有误");
                    }
                    String day = "";
                    if(s.length()==1){
                        day= year+"-07"+"-0"+s;
                    }else  if(s.length()==2){
                        day = year+"-07"+"-"+s;
                    }
                    julyString +=day+",";
                   /* SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date parse = simpleDateFormat.parse(s);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(parse);
                        int year = calendar.get(Calendar.YEAR);
                        int month = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始，需要加1
                        int day = calendar.get(Calendar.DAY_OF_MONTH);

                        if(isSameMonth(year,month,day,7)){
                            july += s+",";
                        }else{
                            errors.add("序号为" + entity.getNum() + "行数据七月值班日期有误，格式为：2024-07-01,2024-07-02");
                        }

                    } catch (ParseException e) {
                        errors.add("序号为" + entity.getNum() + "行数据七月值班日期有误，格式为：2024-07-01,2024-07-02");

                    }*/

                }
                entity.setJuly(julyString.substring(0,julyString.length()-1));
            }

            if (StringUtils.isNotEmpty(entity.getAugust())) {
                String[] augustSplit = entity.getAugust().split("、");
                String augustString = "";
                for (String s : augustSplit) {

                    if(Integer.valueOf(s) > 31){
                        errors.add("序号为" + entity.getNum() + "行数据八月值班日期有误");
                    }
                    String day = "";
                    if(s.length()==1){
                        day= year+"-08"+"-0"+s;
                    }else  if(s.length()==2){
                        day = year+"-08"+"-"+s;
                    }
                    augustString +=day+",";
                    /*SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date parse = simpleDateFormat.parse(s);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(parse);
                        int year = calendar.get(Calendar.YEAR);
                        int month = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始，需要加1
                        int day = calendar.get(Calendar.DAY_OF_MONTH);

                        if(isSameMonth(year,month,day,8)){
                            august += s+",";
                        }else{
                            errors.add("序号为" + entity.getNum() + "行数据八月值班日期有误，格式为：2024-08-01,2024-08-02");
                        }

                    } catch (ParseException e) {
                        errors.add("序号为" + entity.getNum() + "行数据八月值班日期有误，格式为：2024-08-01,2024-08-02");

                    }*/
                }
                entity.setAugust(augustString.substring(0,augustString.length()-1));
            }

            if (StringUtils.isNotEmpty(entity.getSeptember())) {
                String[] septemberSplit = entity.getSeptember().split("、");
                String septemberString = "";
                for (String s : septemberSplit) {
                    if(Integer.valueOf(s) > 30){
                        errors.add("序号为" + entity.getNum() + "行数据七月值班日期有误");
                    }
                    String day = "";
                    if(s.length()==1){
                        day= year+"-09"+"-0"+s;
                    }else  if(s.length()==2){
                        day = year+"-09"+"-"+s;
                    }
                    septemberString +=day+",";
                    /*SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date parse = simpleDateFormat.parse(s);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(parse);
                        int year = calendar.get(Calendar.YEAR);
                        int month = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始，需要加1
                        int day = calendar.get(Calendar.DAY_OF_MONTH);

                        if(isSameMonth(year,month,day,9)){
                            september += s+",";
                        }else{
                            errors.add("序号为" + entity.getNum() + "行数据九月值班日期有误，格式为：2024-09-01,2024-09-02");
                        }

                    } catch (ParseException e) {
                        errors.add("序号为" + entity.getNum() + "行数据九月值班日期有误，格式为：2024-09-01,2024-09-02");

                    }*/
                }
                entity.setSeptember(septemberString.substring(0,septemberString.length()-1));
            }

         /*   entity.setJune(june);
            entity.setJuly(july);
            entity.setAugust(august);
            entity.setSeptember(september);*/
            if (user != null) {
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<DutyImportVo> entities) {
        // 找出所有值班人员的所在单位，在值班主表中找到记录，如有取id，没有创建主表记录

        List<DutyImportVo> inserts = new ArrayList<>();

        if(entities.size()>0){
            for (DutyImportVo entity : entities) {
                Long deptId = entity.getDeptId();
                Duty duty = dutyMapper.selectDutyByDeptId(deptId);

                Long dutyId;
                if(duty != null){
                    dutyId = duty.getId();
                    entity.setJune(mergeAndSortDates(entity.getJune(), null));
                    entity.setJuly(mergeAndSortDates(entity.getJuly(), null));
                    entity.setAugust(mergeAndSortDates(entity.getAugust(), null));
                    entity.setSeptember(mergeAndSortDates(entity.getSeptember(), null));
                    entity.setDutyId(dutyId);
                    inserts.add(entity);

                    DutyDetails detail = dutyDetailsMapper.selectByDutyIdAndWorkId(dutyId, entity.getWorkerId());
                    if (detail != null) {
                        dutyDetailsMapper.deleteDutyDetailsById(detail.getId());
                    }
                }else{
                    Duty duty1 = new Duty();
                    duty1.setDeptId(deptId);
                    dutyMapper.insertDuty(duty1);
                    dutyId = duty1.getId();

                    entity.setDutyId(dutyId);
                    inserts.add(entity);
                }
            }
        }


        if (inserts != null && inserts.size() > 0) {
            if (inserts.size() >= 200) {
                int index = 0;
                while (index <= inserts.size()) {
                    int last = Math.min(index + 200, inserts.size());
                    List<DutyImportVo> temp = inserts.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        dutyDetailsMapper.batchSave(inserts);
                    }
                    index += 200;
                }
            } else {
                dutyDetailsMapper.batchSave(inserts);
            }
        }
    }

    private static List<String> extractAndDeduplicateNames(List<DutyImportVo> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (DutyImportVo entity : entities) {
            uniqueNamesSet.add(entity.getDeptName());
        }

        return new ArrayList<>(uniqueNamesSet);
    }

    private static List<String> extractAndDeduplicateUserNames(List<DutyImportVo> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (DutyImportVo entity : entities) {
            uniqueNamesSet.add(entity.getWorker());
        }

        return new ArrayList<>(uniqueNamesSet);
    }

    private static String mergeAndSortDates(String june1, String june2) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 合并并过滤掉空字符串或null值
        Set<LocalDate> datesSet = new TreeSet<>();

        if (june1 != null && !june1.isEmpty()) {
            datesSet.addAll(Arrays.stream(june1.split(","))
                    .map(date -> LocalDate.parse(date, formatter))
                    .collect(Collectors.toSet()));
        }

        if (june2 != null && !june2.isEmpty()) {
            datesSet.addAll(Arrays.stream(june2.split(","))
                    .map(date -> LocalDate.parse(date, formatter))
                    .collect(Collectors.toSet()));
        }

        // 将排序后的LocalDate对象格式化为字符串并拼接成一个字符串
        return datesSet.stream()
                .map(date -> date.format(formatter))
                .collect(Collectors.joining(","));
    }

}
